package com.lmm.lcbusiness.lcbusiness.pages.rnpages;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.ArrayMap;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.igexin.sdk.PushManager;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.lmm.dresswisdom.lmmframe.components.dialog.DefaultWaitDialog;
import com.lmm.dresswisdom.lmmframe.reactnative.BaseRNActivity;
import com.lmm.dresswisdom.lmmframe.reactnative.RNJsBridgeCallAction;
import com.lmm.dresswisdom.lmmframe.reactnative.RNJsBridgeManager;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;
import com.lmm.lcbusiness.lcbusiness.cominterface.UploadCallBack;
import com.lmm.lcbusiness.lcbusiness.config.ReqCodeValue;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.ChooseMapLocationPlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.ChoosePlacePlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.EditRichContentPlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.GetConfigvaluePlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.GetGoodsAttrRelationPlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.GetGoodsCategoryPlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.GetItemValuePlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.HideLoadingPlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.LogoutPlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.NaviPlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.SetConfigvaluePlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.ShowInfoPlugin;
import com.lmm.lcbusiness.lcbusiness.pages.rnpages.plugins.ShowLoadingPlugin;
import com.lmm.lcbusiness.lcbusiness.server.DemoIntentService;
import com.lmm.lcbusiness.lcbusiness.server.DemoPushService;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xmgong
 * @date 2017/10/31
 * RN容器
 */

@SuppressLint("Registered")
@Route(path = "/app/rnactivity")
public class ReactNativeActivity extends BaseRNActivity implements TakePhoto.TakeResultListener, InvokeListener {
    TakePhoto takePhoto;
    /**
     * 拍照后图片文件
     */
    File takePhotoImgFile;
    /**
     * 文件夹名称
     */
    String QiNiuTag = "";
    String QiNiuToken = "";
    /**
     * 图片上传后网络地址
     **/
    String picUrls = "";
    /**
     * 回调
     */
    Map<String, Callback> mapCallBack = new ArrayMap();


    @Override
    public void addPlugins() {
        registerAction();

        new ChoosePlacePlugin(this);
        new EditRichContentPlugin(this);
        new ShowInfoPlugin(this);
        new SetConfigvaluePlugin(this);
        new GetConfigvaluePlugin(this);
        new GetGoodsCategoryPlugin(this);
        new LogoutPlugin(this);
        new ShowLoadingPlugin(this);
        new HideLoadingPlugin(this);
        new ChooseMapLocationPlugin(this);
        new GetGoodsAttrRelationPlugin(this);
        new GetItemValuePlugin(this);
        new NaviPlugin(this);
    }


    public void registerAction() {
        RNJsBridgeManager.get().registerAction("photoUtils", new RNJsBridgeCallAction() {
            @Override
            public void call(Map<String, Object> map, Callback callback) {
                mapCallBack.put("photoUtils", callback);
                String type = map.get("type").toString();
                int width = (int) map.get("size_w");
                int height = (int) map.get("size_h");

                QiNiuTag = map.get("filetag").toString();
                if (QiNiuTag == null || QiNiuTag.length() == 0) {
                    QiNiuTag = "android";
                }
                QiNiuToken = map.get("token").toString();

                if (!takePhotoImgFile.getParentFile().exists()) {
                    takePhotoImgFile.getParentFile().mkdirs();
                }
                CompressImageImpl();
                if (type.equals("takephoto")) {
                    //拍照
                    if (width == 0 || height == 0) {
                        //不裁剪
                        getTakePhoto().onPickFromCapture(Uri.fromFile(takePhotoImgFile));
                    } else {
                        //裁剪
                        getTakePhoto().onPickFromCaptureWithCrop(Uri.fromFile(takePhotoImgFile),
                                new CropOptions.Builder().setAspectX(width).setAspectY(height).setWithOwnCrop(true)
                                        .create());
                    }
                } else if (type.equals("choose")) {
                    //选择相册
                    if (width == 0 || height == 0) {
                        //不裁剪
                        getTakePhoto().onPickFromGallery();
                    } else {
                        //裁剪
                        getTakePhoto().onPickFromGalleryWithCrop(Uri.fromFile(takePhotoImgFile),
                                new CropOptions.Builder().setAspectX(width).setAspectY(height).setWithOwnCrop(true)
                                        .create());
                    }
                } else {
                    ToastUtils.showToastShort("photoUtils方法中,type参数不对");
                }
            }
        });

        RNJsBridgeManager.get().registerAction("chooseCity", new RNJsBridgeCallAction() {
            @Override
            public void call(Map<String, Object> map, Callback callback) {
                mapCallBack.put("chooseCity", callback);
                ARouter.getInstance().build("/app/choosecity")
                        .navigation(ReactNativeActivity.this, ReqCodeValue.ReqCode_ChooseCity);
            }
        });

    }

    @Override
    public String getJsRootName() {
        return "DressWisdomApp";
    }

    @Override
    public boolean setDebug() {
        return true;
    }

    @Override
    public List<ReactPackage> setOtherPackages() {
        List<ReactPackage> pkgs = new ArrayList<>();
//        pkgs.add(new SvgPackage());
        return pkgs;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        /*强制竖屏*/
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        PushManager.getInstance().initialize(this.getApplicationContext(),
                DemoPushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(),
                DemoIntentService.class);
        takePhotoImgFile = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        processExtraData();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        processExtraData();
    }


    private void processExtraData() {
        if (getIntent().hasExtra("router")) {
            String routr = getIntent().getStringExtra("router");
            Uri uri = Uri.parse(routr);
            String path = "";
            if (uri.getEncodedPath() != null && uri.getEncodedPath().length() > 0) {
                path = uri.getEncodedPath();
            }
            WritableMap map = Arguments.createMap();
            for (String key : uri.getQueryParameterNames()) {
                map.putString(key, uri.getQueryParameter(key));
            }
            map.putString("routeKey", path);
            sendEvent("GotoRoute", map);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ReqCodeValue.ReqCode_ChooseCity) {
            if (resultCode == RESULT_OK) {
                String shen = data.getStringExtra("shen");
                String shi = data.getStringExtra("shi");
                String xian = data.getStringExtra("xian");
                String city = data.getStringExtra("city");
                String code = data.getStringExtra("code");

                if (mapCallBack.containsKey("chooseCity")) {
                    WritableMap writableMap = Arguments.createMap();
                    writableMap.putString("shen", shen);
                    writableMap.putString("shi", shi);
                    writableMap.putString("xian", xian);

                    writableMap.putString("city", city);
                    writableMap.putString("code", code);
                    mapCallBack.get("chooseCity").invoke(writableMap);
                }
            }
        } else if (requestCode == ReqCodeValue.ChoosePointReqCode) {
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    double lat = data.getDoubleExtra("lat", 0);
                    double lon = data.getDoubleExtra("lon", 0);
                    if (lat == 0 && lon == 0) {
                        ToastUtils.showToastShort("位置获取失败!");
                        return;
                    } else {
                        WritableMap map = new WritableNativeMap();
                        map.putDouble("lat", lat);
                        map.putDouble("lon", lon);
                        getCallBack("chooseMapLocation").invoke(map);
                    }
                }
            }
        } else if (requestCode == ReqCodeValue.ReqCode_EditRichTxt) {
            if (resultCode == RESULT_OK) {
                String value = data.getStringExtra("value");
                WritableMap map = Arguments.createMap();
                map.putString("value", value);
                getCallBack("editRichContent").invoke(map);
            }
        }
    }


    private TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(final TResult result) {
        if (result.getImages().size() > 0) {
            picUrls = "";
            showDefaultDialog();
            for (TImage image : result.getImages()) {
                ReactNativePresent.uploadImg(QiNiuToken, QiNiuTag, new File(image.getOriginalPath()), new UploadCallBack() {
                    @Override
                    public void uploadFinish(String netaddress) {
                        if (result.getImages().size() > 1) {
                            picUrls += netaddress + ";";
                            if (picUrls.split(";").length == result.getImages().size()) {
                                hideDefaultDialog();
                                //开始回调
                                if (mapCallBack.containsKey("chooseMultiImgs")) {
                                    WritableMap writableMap = Arguments.createMap();
                                    writableMap.putString("imgs", picUrls);
                                    mapCallBack.get("chooseMultiImgs").invoke(writableMap);
                                }
                            }
                        } else {
                            picUrls = netaddress;
                            hideDefaultDialog();
                            //开始回调
                            if (mapCallBack.containsKey("photoUtils")) {
                                WritableMap writableMap = Arguments.createMap();
                                writableMap.putString("imgs", picUrls);
                                mapCallBack.get("photoUtils").invoke(writableMap);
                            }
                        }
                    }
                });
            }
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }

    private InvokeParam invokeParam;

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }


    DefaultWaitDialog defaultWaitDialog;

    public void showDefaultDialog() {
        if (this.defaultWaitDialog == null) {
            this.defaultWaitDialog = new DefaultWaitDialog(this);
        }
        this.defaultWaitDialog.ShowDialog();
    }

    public void hideDefaultDialog() {
        if (this.defaultWaitDialog == null) {
            this.defaultWaitDialog = new DefaultWaitDialog(this);
        }
        this.defaultWaitDialog.HideDialog();
    }


    public void CompressImageImpl() {
        CompressConfig config = new CompressConfig.Builder()
                .setMaxSize(50 * 1024)
                .setMaxPixel(800)
                .create();
        getTakePhoto().onEnableCompress(config, true);
    }


}
